package com.fourth;

/**
 * Author Name: Justice
 * Project Name: Stage11
 * File Name: BinarySearchTree
 * Package Name: com.fourth
 * Date: 2020-03-22 21:41
 * Copyright (c) 2020,All Rights Reserved.
 */


public class BinarySearchTree {
    private Node root; //根节点

    // 提供给外部调用的方法
    public void add(int data) {
        if (root == null) {
            root = new Node(data);
        } else {
            root.addNode(data);
        }
    }

    //提供给外部调用的方法
    void print() {
        root.printNode();
    }

    //节点类
    private class Node {
        private int data; //数据
        private Node left; //左节点
        private Node right; //右节点

        Node(int data) {
            this.data = data;
        }

        //添加节点（不考虑根节点的情况）
        void addNode(int data) {
            if (data < this.data) {
                if (this.left == null) {
                    this.left = new Node(data);
                } else {
                    this.left.addNode(data);
                }
            } else {
                if (this.right == null) {
                    this.right = new Node(data);
                } else {
                    this.right.addNode(data);
                }
            }
        }

        //输出节点(中序遍历: 左中右)
        void printNode() {
            //输出左边
            if (this.left != null) {
                this.left.printNode();
            }
            //输出中间
            System.out.print(this.data + ">>");

            //输出右边
            if (this.right != null) {
                this.right.printNode();
            }
        }
    }
}
